import cookie from 'js-cookie'
import { isClient } from '@/app/utils'
import notification from '@/app/components/hooks/useNotification'
import { useStore } from '@/store'

const baseUrl = 'https://www.cjasen.com/v14'
const baseUrl2 = 'http://localhost:3001'
function addBaseUrl(url) {
  // return process.title !== 'browser' && process.env.NODE_ENV !== 'development' ? baseUrl2 : baseUrl
  if (url.includes('http')) {
    return url
  }
  return baseUrl2 + url
}
interface Params {
  url: string
  method: 'POST' | 'GET'
  data: Record<string, any>
  token?: string
  hideLoding?: boolean
}

export default function Fetch({
  url,
  method = 'GET',
  data = {},
}: Params): Promise<any> {
  if (method === 'POST') {
    return fetch(addBaseUrl(url), {
      body: JSON.stringify(data),
      mode: 'cors',
      headers: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${data.token || cookie.get('baijie_token') || ''}`,
      },
      method,
      // credentials: 'include',
      cache: 'no-cache',
    }).then(async (response) => {
      const res = await response.json()
      if (res.code !== 200) {
        if (isClient()) {
          if (res.code === 401) {
            useStore.setState({ showLogin: true })
          }
          else {
            notification({
              message: res.msg,
            })
          }
        }
      }
      return Promise.resolve(res)
    })
  }
  const { token, ...rest } = data
  const params = rest ? new URLSearchParams(rest) : null
  return fetch(`${addBaseUrl(url)}${params ? `?${params}` : ''}`, {
    headers: {
      'content-type': 'application/json',
      'Authorization': `Bearer ${token || cookie.get('baijie_token') || ''}`,
    },
    mode: 'cors',
    // credentials: 'include',
    cache: 'no-cache',
    method: method || 'get',
  }).then(async (response) => {
    const res = await response.json()
    if (res.code !== 200) {
      if (isClient()) {
        if (res.code === 401) {
          useStore.setState({ showLogin: true })
        }
        else {
          notification({
            message: res.msg,
          })
        }
      }
    }
    return Promise.resolve(res)
  })
}
